<?php

namespace app\common\lib\relation_analysis;

use app\common\cachemodel\Recode;
use app\common\cachemodel\zl1_relation\Zl1RelationAnalysisFitYou;
use app\common\cachemodel\zl1_relation\Zl1RelationAnalysisIdea;
use app\common\cachemodel\zl1_relation\Zl1RelationAnalysisIdeaRecodeInfo;
use app\common\cachemodel\zl1_relation\Zl1RelationAnalysisReport;
use app\common\lib\astrolog\AuthenticatePlayboy;
use app\common\lib\astrolog\HowToWooHim;
use app\common\lib\astrolog\IdealLover;
use app\common\lib\astrolog\SuitableLover;
use app\common\lib\Push;
use app\common\lib\Util;
use app\common\model\MessageCenter;
use think\Env;
use think\Log;
use think\queue\Job;

class RelationAnalysisJob
{
    /**
     * 我的理想型 计算
     * @param Job $job
     * @param $jobData
     */
    public function myIdeaTask(Job $job, $jobData)
    {
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
        }
        $nowTime = time();
        $host = Util::getEcsIp();
        $startTime = date('Y-m-d H:i:s');
        $logInfo = "我的理想型计算 开始:{$startTime} host:{$host} uid:{$jobData['uid']} 理想型ID:{$jobData['id']}";

        $relationAnalysisIdeaModel = new Zl1RelationAnalysisIdea();
        try
        {
            // $jobData = [
            //     'id' => $id,
            //     'uid' => $data['uid'],
            //     'rids' => $data['rids'],
            //     'order_id' =>''
            //     'tag_info' => $data['tag_info'],
            //     'is_update' => false // 是否是重新计算
            //     'push_switch' => true // 是否发送消息与推送
            // ];
            $rids = explode(',', $jobData['rids']);
            $tagList = json_decode($jobData['tag_info'], true);
            $utilModel = new Util();

            $selfRecode = (new Recode())->getRecodeLists($jobData['uid'], 1);
            if ($selfRecode)
            {
                unset($selfRecode['uid'], $selfRecode['aid'], $selfRecode['merc'], $selfRecode['venu'], $selfRecode['mars'], $selfRecode['jupi'], $selfRecode['satu'], $selfRecode['non'], $selfRecode['lili'], $selfRecode['juno'], $selfRecode['mc'], $selfRecode['or_day'], $selfRecode['status'], $selfRecode['from'], $selfRecode['is_read']);
                $selfRecode = arrayKeyData2int($selfRecode, ['id', 'isself', 'type', 'year', 'month', 'day', 'hour', 'minute', 'timezone', 'long_deg', 'long_min', 'ew', 'lat_deg', 'lat_min', 'ns', 'is_summer',]);


                $selfRecode['sun'] = mb_substr($utilModel->recodeAstro($selfRecode['sun']), 0, 2);
                $selfRecode['moon'] = mb_substr($utilModel->recodeAstro($selfRecode['moon']), 0, 2);
                $selfRecode['asc'] = mb_substr($utilModel->recodeAstro($selfRecode['asc']), 0, 2);
            } else
            {
                $selfRecode = [];
            }

            $recodeLists = (new Recode())->batchGetInfoByIds($rids, ['id', 'isself', 'name', 'type', 'year', 'month', 'day', 'hour', 'minute', 'timezone', 'birth_country', 'birth_province', 'birth_city', 'live_country', 'live_province', 'live_city', 'comments', 'long_deg', 'long_min', 'ew', 'lat_deg', 'lat_min', 'ns', 'avatar', 'is_summer', 'sun', 'moon', 'asc']);

            foreach ($recodeLists as $rid => $recodeListItem)
            {
                $recodeLists[$rid] = arrayKeyData2int($recodeListItem, ['id', 'isself', 'type', 'year', 'month', 'day', 'hour', 'minute', 'timezone', 'long_deg', 'long_min', 'ew', 'lat_deg', 'lat_min', 'ns', 'is_summer',]);

                $recodeLists[$rid]['sun'] = mb_substr($utilModel->recodeAstro($recodeListItem['sun']), 0, 2);
                $recodeLists[$rid]['moon'] = mb_substr($utilModel->recodeAstro($recodeListItem['moon']), 0, 2);
                $recodeLists[$rid]['asc'] = mb_substr($utilModel->recodeAstro($recodeListItem['asc']), 0, 2);
            }

            $data = IdealLover::getInstance()->setUserRecord($selfRecode)->setRecordList($recodeLists)->setidealTypeIdList(array_values($tagList))->init();

            $resData = [];
            // 数据进行处理，排序
            foreach ($data as $k1 => $v1)
            {
                $total = 0;
                $itemCountNum = count($v1['result']);
                $goodItemNum = 0;
                $notBadItemNUm = 0;
                $result = [];
                foreach ($v1['result'] as $k2 => $v2)
                {
                    $total += $v2['score'];
                    $v2['score'] >= 50 && $goodItemNum++;
                    $v2['ori'] > 0 && $notBadItemNUm++;
                    $result[] = [
                        'id' => $v2['id'],
                        'score' => $v2['score'],
                        'ori' => $v2['ori'],
                    ];
                }

                $probability = ($total / $itemCountNum / 2) + ($notBadItemNUm / $itemCountNum * 30) + ($goodItemNum / $itemCountNum * 20);

                $resData[] = [
                    'rid' => $v1['rid'],
                    'result' => $result,
                    'average' => sprintf("%.2f", $total / $itemCountNum),
                    'probability' => sprintf("%.2f", $probability)
                ];
            }

            $resData = resort($resData, 'probability', 'DESC');

            $updateData = [
                'rid_num' => count($rids),
                'status' => 2,
                'update_time' => $nowTime,
                'content' => json_encode($resData, JSON_UNESCAPED_UNICODE)
            ];

            if (!$jobData['is_update'])
            {
                $updateData['start_time'] = $nowTime;
            }

            $relationAnalysisIdeaModel->UpdateData($jobData['id'], $updateData);

            if ($jobData['is_update'])
            {   // 更新档案信息
                (new Zl1RelationAnalysisIdeaRecodeInfo())->UpdateData($jobData['id'], [
                    'self_recode' => json_encode($selfRecode, JSON_UNESCAPED_UNICODE),
                    'recode_info' => json_encode($recodeLists, JSON_UNESCAPED_UNICODE),
                ]);
            } else
            {   // 写入档案信息
                (new Zl1RelationAnalysisIdeaRecodeInfo())->SaveData([
                    'id' => $jobData['id'],
                    'self_recode' => json_encode($selfRecode, JSON_UNESCAPED_UNICODE),
                    'recode_info' => json_encode($recodeLists, JSON_UNESCAPED_UNICODE),
                ]);
            }

            if (isset($jobData['order_id']))
            {
                $OrdersModel = new \app\common\cachemodel\Orders();
                $OrdersModel->UpdateData($jobData['order_id'], ['status' => 4, 'update_time' => $nowTime], 4);
            }
            if (isset($jobData['push_switch']) && $jobData['push_switch'])
            {
                // 消息中心添加信息
                $messageData = [
                    'status' => 0,
                    'is_read' => 0,
                    'range' => $jobData['uid'],
                    'type' => 2,
                    'reid' => 0,
                    'cid' => 4,//
                    'title' => $jobData['is_update'] ? '理想型重新计算完成' : '理想型计算完成',
                    'content' => $jobData['is_update'] ? '您购买的理想型方案已经重新计算成功，点击查看计算结果！' : '您购买的理想型方案已经计算成功，点击查看计算结果！',
                    'link' => "relation_research_ideal_result?id={$jobData['id']}&need_auth=2",
                    'target' => 'local',
                    'create_time' => $nowTime
                ];
                // 发送站内信
                (new MessageCenter())->pushMessage($jobData['uid'], $messageData);
            }
        }
        catch (\Exception $e)
        {
            Log::write('我的理想型计算 RelationAnalysisJob model => myIdeaTask()异常;JobData:【' . json_encode($jobData, JSON_UNESCAPED_UNICODE) . '】错误消息：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');

            $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
        }

        $logInfo .= ' jobData:' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        print(date('Y-m-d H:i:s') . ' ' . $logInfo);
        Log::write($logInfo, 'log', true);

        $job->delete();
    }

    /**
     * 适合你的Ta   计算
     * @param Job $job
     * @param $jobData
     */
    public function fitYouTask(Job $job, $jobData)
    {
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
        }
        $nowTime = time();
        $host = Util::getEcsIp();
        $startTime = date('Y-m-d H:i:s');
        $logInfo = "适合你的Ta 计算 开始:{$startTime} host:{$host} ";
        try
        {
            $logInfo .= "uid:{$jobData['uid']}";

            // $jobData = [
            //     'uid' => $uid,
            //     'recode' => $recode,
            //     'unlock_gids' => $unlcok_gids,
            //     'order_id' => $order_id,
            //     'push_switch' => true // 是否发送消息与推送
            // ];

            asort($jobData['unlock_gids']);

            $logicTypeConfig = [
                84 => 11,
                85 => 12,
                86 => 13,
            ];

            $logicType = [];
            foreach ($jobData['unlock_gids'] as $gidItem)
            {
                $logicType[] = $logicTypeConfig[$gidItem];
            }

            $relationAnalysisFitYou = new Zl1RelationAnalysisFitYou();

            $fitYou = $relationAnalysisFitYou->where(['order_num' => $jobData['order_id']])->column('gid', 'id');

            $logicResult = SuitableLover::getInstance()->setUserRecord($jobData['recode'])->setLogicType($logicType)->init();

            if (empty($logicResult))
            {
                foreach ($fitYou as $id => $gid)
                {
                    $relationAnalysisFitYou->UpdateData($jobData['uid'], $jobData['recode']['id'], ['status' => 3, 'update_time' => $nowTime], ['id' => $id]);
                }

                $logInfo .= "计算失败";
            } else
            {
                foreach ($fitYou as $id => $gid)
                {
                    $resData = json_encode($logicResult[$logicTypeConfig[$gid]], JSON_UNESCAPED_UNICODE);

                    $relationAnalysisFitYou->UpdateData($jobData['uid'], $jobData['recode']['id'], ['status' => 2, 'update_time' => $nowTime, 'content' => $resData], ['id' => $id]);
                }

                $OrdersModel = new \app\common\cachemodel\Orders();
                $OrdersModel->UpdateData($jobData['order_id'], ['status' => 4, 'update_time' => $nowTime], 4);

                if (count($logicType) === 3)
                {
                    $name = '适合你的那个TA-全部';
                } else
                {
                    $nameConfig = [
                        11 => '适合你的那个TA-终极契合型',
                        12 => '适合你的那个TA-甜蜜幸福型',
                        13 => '适合你的那个TA-虐恋型',
                    ];

                    $name = '';
                    foreach ($logicType as $type)
                    {
                        $name .= $nameConfig[$type] . '和';
                    }

                    $name = rtrim($name, '和');
                }
                if (isset($jobData['push_switch']) && $jobData['push_switch'])
                {
                    // 消息中心添加信息
                    $messageData = [
                        'status' => 0,
                        'is_read' => 0,
                        'range' => $jobData['uid'],
                        'type' => 2,
                        'reid' => 0,
                        'cid' => 4,//
                        'title' => '报告计算完成',
                        'content' => '您购买的' . $name . '已经计算成功，点击查看计算结果！',
                        'link' => Env::get('host.domain') . "/web/relation_research_fit_you/index?rid={$jobData['recode']['id']}&order_id={$jobData['order_id']}&tab_gid={$jobData['unlock_gids'][0]}&need_auth=1&zhunle_not_show_nav=1&zhunle_nav_text_color=1",
                        'target' => 'link',
                        'create_time' => $nowTime
                    ];
                    // 发送站内信
                    (new MessageCenter())->pushMessage($jobData['uid'], $messageData);
                }
            }
        }
        catch (\Exception $e)
        {
            Log::write('RelationAnalysisJob model => fitYouTask()异常：' . $e->getMessage() . '失败行数：' . $e->getLine() . ';JobData:' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 'error');

            $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
        }

        $logInfo .= ' jobData:' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        print(date('Y-m-d H:i:s') . ' ' . $logInfo);
        Log::write($logInfo, 'log', true);

        $job->delete();
    }

    /**
     * 关系研究所报告  计算
     * @param Job $job
     * @param $jobData
     */
    public function reportTask(Job $job, $jobData)
    {
        // $jobData = [
        //     'id' => $id,
        //     'uid' => $uid,
        //     'rid1' => $rid1,
        //     'rid2' => $rid2,
        //     'type' => $type,     // 报告类型 1=>怎么追求Ta  2=>鉴“渣”神器
        //     'gid' => $gid,
        //     'recodes' => $recodeDatas
        //     'order_id' => $order_id,
        //     'push_switch' => true // 是否发送消息与推送
        // ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
        }
        $res = false;
        $nowTime = time();
        $host = Util::getEcsIp();
        $startTime = date('Y-m-d H:i:s');
        $typeName = $jobData['type'] === 1 ? '怎么追求Ta' : '鉴“渣”神器';
        $logInfo = "关系研究所报告 {$typeName}计算 开始:{$startTime} host:{$host} uid:{$jobData['uid']} ";

        try
        {
            $relationAnalysisReportModel = new Zl1RelationAnalysisReport();
            $OrdersModel = new \app\common\cachemodel\Orders();
            // 计算方法
            if ($jobData['type'] === 1)
            {
                $content = HowToWooHim::getInstance()->setUserRecord([$jobData['recodes']['recode1'], $jobData['recodes']['recode2']])->init();
            } else
            {
                $content = AuthenticatePlayboy::getInstance()->setUserRecord($jobData['recodes']['recode1'])->init();
            }

            $relationAnalysisReportModel->UpdateData($jobData['id'], $jobData['uid'], $jobData['type'], $jobData['rid1'], $jobData['rid2'], [
                'status' => 2,
                'content' => json_encode($content, JSON_UNESCAPED_UNICODE),
                'start_time' => $nowTime,
                'update_time' => $nowTime
            ]);

            $OrdersModel->UpdateData($jobData['order_id'], ['status' => 4, 'update_time' => $nowTime], 4);

            $res = true;
        }
        catch (\Exception $e)
        {
            Log::write('RelationAnalysisJob model => reportTask()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');

            $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
        }

        if ($res && isset($jobData['push_switch']) && $jobData['push_switch'])
        {
            try
            {
                if ($jobData['type'] === 1)
                {
                    $messageLink = Env::get('host.domain') . "/web/relation_research_fit_you/follow?rid1={$jobData['rid1']}&rid2={$jobData['rid2']}&order_id={$jobData['order_id']}&history_id={$jobData['id']}&need_auth=2&zhunle_not_show_nav=1&zhunle_nav_text_color=1";
                } else
                {
                    $messageLink = Env::get('host.domain') . "/web/relation_research_fit_you/check_player?rid={$jobData['rid1']}&order_id={$jobData['order_id']}&history_id={$jobData['id']}&need_auth=2&zhunle_not_show_nav=1&zhunle_nav_text_color=1";
                }
                $msg = '您购买的' . $typeName . '已经计算完成了，点击查看详情！';
                // 消息中心添加信息
                $messageData = [
                    'status' => 0,
                    'is_read' => 0,
                    'range' => $jobData['uid'],
                    'type' => 2,
                    'reid' => 0,
                    'cid' => 4,
                    'title' => '报告计算完成',
                    'content' => $msg,
                    'link' => $messageLink,
                    'target' => 'link',
                    'create_time' => $nowTime
                ];
                // 发送站内信
                (new MessageCenter())->pushMessage($jobData['uid'], $messageData);
                // PUSH推送报告
                $pushRes = (new Push())->pushUserMsg($jobData['uid'], $msg, ['target' => 'link', 'link' => $messageLink, 'action' => 'extend']);
                if (!$pushRes['success'])
                {
                    $logInfo .= ' error: 计算完成,推送失败 message:' . $pushRes['message'];
                }
            }
            catch (\Exception $e)
            {
                Log::write('RelationAnalysisJob model => reportTask() 发送消息异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            }
        }

        $logInfo .= ' jobData:' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        print(date('Y-m-d H:i:s') . ' ' . $logInfo);
        Log::write($logInfo, 'log', true);

        $job->delete();
    }
}
